import {AsyncStorage} from 'react-native'
import {configure, action, runInAction, observable} from 'mobx'
import Auth from '../service/Auth'
configure({enforceActions: 'observed'})

class UserAuth {
    constructor (){
        this._getLoginInfo()
    }
    @observable token = undefined

    @observable currentUser = {}

    @observable userById = {}

    @action getSmsCode= (payload) => {
        return Auth.GetSmsCode(payload)
    }
    @action Login= (payload) => {
        return Auth.Login(payload).then((res)=>{
            runInAction(()=>{
                this.token = res.data.token
                this.currentUser = res.data.user
                this.userById[res.data.user.id] = res.data.user
                AsyncStorage.setItem('token', res.data.token)
                AsyncStorage.setItem('currentUser', JSON.stringify(res.data.user))
            })
        })
    }
    @action Regist= (payload) => {
        return Auth.Regist(payload).then((res)=>{
            runInAction(()=>{
                this.token = res.data.token
                this.currentUser = res.data.user
                this.userById[res.data.user.id] = res.data.user
                AsyncStorage.setItem('token', res.data.token)
                AsyncStorage.setItem('currentUser', JSON.stringify(res.data.user))
            })
        })
    }
    @action findPassword = (payload) => {
        return Auth.findPassword(payload)
    }


    @action fetchCurrentUserInfo = (payload) => {
        return Auth.fetchCurrentUserInfo(payload).then((res) => {
            runInAction(()=>{
                this.currentUser = res.data
                this.userById[res.data.id] = res.data
            })
        })
    }

    @action auth = (payload) => {
        return Auth.auth(payload).then((res)=>{
            runInAction(()=>{
                this.currentUser.real_name_status = 1
                this.currentUser.real_name = payload.name
                this.currentUser.id_card = payload.id_card
            })
            return res
        })
    }


    async _getLoginInfo() {
        let token = await AsyncStorage.getItem('token')
        if(token){
            let currentUser = await AsyncStorage.getItem('currentUser')
            runInAction(()=>{
                this.token = token
                this.currentUser = JSON.parse(currentUser)
                this.userById[this.currentUser.id] = this.currentUser
            })
        }

    }
}

export default UserAuth